import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login/index.vue') // 路由懒加载  注释表示打包分类
  },
  {
    path: '/reg',
    name: 'Reg',
    component: () => import('../views/Reg/index.vue') // 路由懒加载  注释表示打包分类
  },
  /* 首页入口 */
  /*
  如果二级路由写了 /  就不需要根据一级路由来查找
  如果二级路由没有写 /  需要根据一级路由来进行拼接查找
   */
  {
    path: '/',
    component: () => import('../views/Layout/index.vue'),
    children: [
      { path: '', component: () => import('../views/Home/index.vue') },
      { path: 'artCategory', component: () => import('../views/art/artcategory.vue') },
      { path: 'artlist', component: () => import('../views/art/artlist.vue') },
      { path: 'userinfo', component: () => import('../views/user/userinfo.vue') },
      { path: 'changeavatar', component: () => import('../views/user/changeavatar.vue') },
      { path: 'resetpwd', component: () => import('../views/user/resetpwd.vue') }
    ]
  }
]
const router = new VueRouter({
  routes
})

// 路由前置导航守卫
// 白名单列表
const whitelist = ['/login', '/reg']
router.beforeEach((to, from, next) => {
  // 先判断是否访问的是有权限的页面
  console.log(to.path, whitelist.includes(to.path))
  if (whitelist.includes(to.path) === true) {
    // 用户访问的是登录或者注册页面 不需要拦截 直接放行
    next()
  } else {
    // 进入else分支说明用户访问的是有权限的页面, 先判断是否有token
    // 如果有token直接放行
    if (localStorage.getItem('token')) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
